package com.shop.servlet;

import com.shop.model.Student;
import com.shop.service.IStudentService;
import com.shop.service.StudentService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Objects;

@WebServlet("/change-password")
public class ChangepasswordServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String studentId = req.getParameter("studentId");
        String oldpassword = req.getParameter("oldpassword");
        String newpassword = req.getParameter("newpassword");
        String newpassword2 = req.getParameter("newpassword2");

        IStudentService istudentService = new StudentService();
        Student student = istudentService.search(studentId);
        if(Objects.equals(student.getPassword(), oldpassword)){
            if(newpassword.equals(newpassword2)){
                if(istudentService.updatePassword(studentId,newpassword)){
                    req.getRequestDispatcher("login.jsp").forward(req, resp);
                }
            }else {
                req.setAttribute("error", "两次密码不一致！");
                req.getRequestDispatcher("changepassword.jsp").forward(req, resp);
            }
        }else {
            req.setAttribute("error", "输入的旧密码错误！");
            req.getRequestDispatcher("changepassword.jsp").forward(req, resp);
        }
    }
}
